package com.chenyue.cm.match.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.live.vo.LiveUserMatchHistory;
import com.chenyue.cm.match.dao.JdMatchFormatMemberMapper;
import com.chenyue.cm.match.dao.JdMatchItemRelationMapper;
import com.chenyue.cm.match.dao.JdMatchLiveUserMapper;
import com.chenyue.cm.match.dao.ex.MatchLiveUserMapperEx;
import com.chenyue.cm.match.domain.JdMatchFormat;
import com.chenyue.cm.match.domain.JdMatchFormatMember;
import com.chenyue.cm.match.domain.JdMatchItemRelation;
import com.chenyue.cm.match.domain.JdMatchLiveUser;
import com.chenyue.cm.match.service.JdMatchLiveUserService;
import com.chenyue.cm.match.vo.MatchScore;
import com.chenyue.cm.match.vo.MatchScoreList;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author chenyue-cm
 */
@Service(value = "JdMatchLiveUserService")
public class JdMatchLiveUserServiceImpl extends BaseServiceImpl<JdMatchLiveUser> implements JdMatchLiveUserService {

    private final JdMatchLiveUserMapper jdMatchLiveUserMapper;

    private final MatchLiveUserMapperEx matchLiveUserMapperEx;

    private final JdMatchItemRelationMapper matchItemRelationMapper;

    private final JdMatchFormatMemberMapper matchFormatMemberMapper;

    public JdMatchLiveUserServiceImpl(
            @Qualifier("jdMatchLiveUserMapper") JdMatchLiveUserMapper jdMatchLiveUserMapper,
            MatchLiveUserMapperEx matchLiveUserMapperEx,
            @Qualifier("jdMatchItemRelationMapper") JdMatchItemRelationMapper matchItemRelationMapper,
            @Qualifier("jdMatchFormatMemberMapper") JdMatchFormatMemberMapper matchFormatMemberMapper
    ) {
        this.jdMatchLiveUserMapper = jdMatchLiveUserMapper;
        this.matchLiveUserMapperEx = matchLiveUserMapperEx;
        this.matchItemRelationMapper = matchItemRelationMapper;
        this.matchFormatMemberMapper = matchFormatMemberMapper;
    }

    @Override
    @Resource(name = "jdMatchLiveUserMapper")
    public void setBaseMapper(LcBaseMapper<JdMatchLiveUser, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    /**
     * 查询参赛历史 总数
     *
     * @param userId 用户id
     * @return int
     */
    @Override
    public Integer liveUserMatchHistoryCount(Integer userId) {
        return jdMatchLiveUserMapper.selectCount(
                new LambdaQueryWrapper<JdMatchLiveUser>()
                        .eq(JdMatchLiveUser::getUserId, userId)
        );
    }

    /**
     * 查询参赛历史
     *
     * @param userId      用户id
     * @param convertPage 分页内容
     * @return list
     */
    @Override
    public List<LiveUserMatchHistory> liveUserMatchHistoryList(Integer userId, String convertPage) {
        return matchLiveUserMapperEx.liveUserMatchHistoryList(userId, convertPage);
    }

    /**
     * 获取参赛员历史总分
     *
     * @param id 参赛员userId
     * @return 最高总分
     */
    @Override
    public Integer historyRecord(Integer id) {
        return matchLiveUserMapperEx.historyRecordScore(id);
    }

    /**
     * 获取参赛员历史排名
     *
     * @param id 参赛员userId
     * @return 最高排名
     */
    @Override
    public Integer historyRank(Integer id) {
        return matchLiveUserMapperEx.historyRecordRank(id);
    }

    /**
     * 查询直播间参赛员
     *
     * @param recordId 直播id
     * @param itemId   项目id
     * @param groupId  团队id
     * @param page     分页详情
     * @return MatchMemberList
     */
    @Override
    public List<MatchScoreList.MatchMemberList> matchMemberScoreList(Integer recordId, Integer itemId, Integer groupId, String page) {
        return matchLiveUserMapperEx.matchMemberScoreList(recordId, itemId, groupId, page);
    }

    /**
     * 查询直播间参赛员
     *
     * @param recordId 直播id
     * @param itemId   项目id
     * @param groupId  分组id
     * @return count
     */
    @Override
    public int matchMemberScoreListCount(Integer recordId, Integer itemId, int groupId) {
        return matchLiveUserMapperEx.matchMemberScoreListCount(recordId, itemId, groupId);
    }

    /**
     * 查询直播间分配的团队
     *
     * @param recordId 直播id
     * @param itemId   项目id
     * @param page     分页参数
     * @return MatchMemberList
     */
    @Override
    public List<MatchScoreList.MatchGroupList> matchGroupScoreList(Integer recordId, Integer itemId, String page) {
        return matchLiveUserMapperEx.matchGroupScoreList(recordId, itemId, page);
    }

    /**
     * 查询直播间分配的团队
     *
     * @param recordId 直播id
     * @param itemId   项目id
     * @return MatchMemberList
     */
    @Override
    public int matchGroupScoreListCount(Integer recordId, Integer itemId) {
        return matchLiveUserMapperEx.matchGroupScoreListCount(recordId, itemId);
    }

    /**
     * 赛程下参赛员
     *
     * @param formatId 赛程id
     * @param itemId   项目id
     * @param groupId  分组id
     * @return MatchMemberList
     */
    @Override
    public List<MatchScoreList.MatchMemberList> matchMemberScoreList(String formatId, Integer itemId, Integer groupId) {
        return matchLiveUserMapperEx.handlePromotionScoreList(formatId, itemId, groupId);
    }

    /**
     * 查询直播间分配的团队
     *
     * @param formatId 直播id
     * @param itemId   项目id
     * @return MatchMemberList
     */
    @Override
    public List<MatchScoreList.MatchGroupList> matchGroupScoreList(String formatId, Integer itemId) {
        return matchLiveUserMapperEx.handlePromotionGroupList(formatId, itemId);
    }

    /**
     * 核算成绩 计算排名
     *
     * @param format 赛程信息
     * @return 晋级人员
     */
    @Override
    public List<JdMatchFormatMember> calculateAndRank(JdMatchFormat format) {
        List<JdMatchFormatMember> result;

        final List<JdMatchItemRelation> itemList = matchItemRelationMapper.selectList(
                new LambdaQueryWrapper<JdMatchItemRelation>()
                        .eq(JdMatchItemRelation::getMatchId, format.getMatchId())
        );

        if (itemList.size() > 1) {
//            多项 取最高两项
            result = matchLiveUserMapperEx.multiCalculate(format.getId());
        } else {
//            单项 直接排名
            result = matchLiveUserMapperEx.singleCalculate(format.getId());
        }

        if (format.getUpdateType() != null && format.getUpdateType() == 0) {
//            自动晋级
            for (int i = 0; i < result.size(); i++) {
                final JdMatchFormatMember formatMember = result.get(i);
                final int rank = i + 1;
                formatMember.setRank(rank);
//                名次小于 晋级总数的 +  晋级
                if (formatMember.getScore() == null) {
                    formatMember.setPromotionState(2);
                } else {
                    formatMember.setPromotionState(1);
                    if (format.getPromotionNum() != null && format.getPromotionNum() > 0) {
                        if (rank > format.getPromotionNum()) {
//                        名次超出
                            formatMember.setPromotionState(2);
                        }
                    }
                    if (format.getPromotionScore() != null && format.getPromotionScore() > 0) {
                        if (formatMember.getScore() < format.getPromotionScore()) {
//                        分数不够
                            formatMember.setPromotionState(2);
                        }
                    }
                }
                matchFormatMemberMapper.update(
                        formatMember,
                        new LambdaQueryWrapper<JdMatchFormatMember>()
                                .eq(JdMatchFormatMember::getUserId, formatMember.getUserId())
                                .eq(JdMatchFormatMember::getFormatId, format.getId())
                );
            }
            return result.stream().filter(o -> o.getPromotionState() == 1).collect(Collectors.toList());
        } else {
            return null;
        }
    }


    /**
     * 查询后台赛程成绩列表
     *
     * @param formatId 赛程id
     */
    @Override
    public List<MatchScore> getMatchScoreList(Integer formatId, Integer page, Integer rows) {
        return matchLiveUserMapperEx.getMatchScoreList(formatId, page, rows);
    }

    /**
     * 查询后台赛程成绩列表
     *
     * @param formatId 赛程id
     */
    @Override
    public long getMatchScoreListCount(Integer formatId) {
        return matchLiveUserMapperEx.getMatchScoreListCount(formatId);
    }
}
